package com.service.user.impl;

import com.dao.LogDao;
import com.service.user.LogService;
import com.utils.SqlSessionGetter;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 提供系统登录、注册、浏览、错误日志相关的功能实现
 *
 * 
 */
@Service
public class LogServiceImpl implements LogService {

  @Override
  public void addARegisterLog(String userId) {
    SqlSession session = SqlSessionGetter.getSqlSession();
    LogDao dao = session.getMapper(LogDao.class);
    dao.insertARegisterLog(userId);
    session.commit();
    session.close();
  }

  @Override
  public void visitorCome(HttpServletRequest httpServletRequest) {
    String ip = getIpAddress(httpServletRequest);
    SqlSession session = SqlSessionGetter.getSqlSession();
    LogDao dao = session.getMapper(LogDao.class);
    dao.insertAVisitLog(ip);
    session.commit();
    session.close();
  }

  @Override
  public void visitorLeave(HttpServletRequest httpServletRequest) {
    String ip = getIpAddress(httpServletRequest);
    SqlSession session = SqlSessionGetter.getSqlSession();
    LogDao dao = session.getMapper(LogDao.class);
    dao.updateVisitLog(ip);
    session.commit();
    session.close();
  }

  @Override
  public void userCome(String userId, HttpServletRequest httpServletRequest) {
    String ip = getIpAddress(httpServletRequest);
    SqlSession session = SqlSessionGetter.getSqlSession();
    LogDao dao = session.getMapper(LogDao.class);
    dao.insertALoginLog(userId, ip);
    session.commit();
    session.close();
  }

  @Override
  public void userLeave(String userId, HttpServletRequest httpServletRequest) {
    String ip = getIpAddress(httpServletRequest);
    SqlSession session = SqlSessionGetter.getSqlSession();
    LogDao dao = session.getMapper(LogDao.class);
    dao.updateLoginLog(userId, ip);
    session.commit();
    session.close();
  }

  @Override
  public int addAErrorLog(String title, String content) {
    SqlSession session = SqlSessionGetter.getSqlSession();
    LogDao dao = session.getMapper(LogDao.class);
    int row = dao.insertAErrorLog(title, content);
    session.commit();
    session.close();
    return row;
  }
}
